from gradio_client import Client, handle_file, file
import time
import requests, json

# pip install gradio_client


def State_Sound_TTS():
    """检测服务状态"""
    try:
        # client = Client("http://soVits:9874/")
        client = requests.get("http://soVits:9872/")
        return client.json() if client and client.status_code == 200 else None
    except BaseException as err:
        print(err)
        return False


def Enable_Sound_TTS(conf, isEnable=True):
    """开关TTS推理功能"""
    try:
        client = Client("http://soVits:9874/")
        # print(client)
        result = client.predict(
            isEnable,  # bool in 'Open TTS inference WEBUI' Checkbox component
            "GPT_SoVITS/pretrained_models/chinese-roberta-wwm-ext-large",  # str in ' Pretrained BERT model path' Textbox component
            "GPT_SoVITS/pretrained_models/chinese-hubert-base",  # str in 'Pretrained SSL model path' Textbox component
            "0",  # str in 'GPU number, can only input ONE integer' Textbox component
            conf["gptmodels"],  # str in '*GPT models list' Dropdown component
            conf["sovitsmodels"],  # str in '*SoVITS models list' Dropdown component
            fn_index=23,
        )
        print(result)
    except BaseException as err:
        print(err)
        return False
    return (
        True
        if result
        in [
            "TTS inference is enabled",
            "TTS inference process closed",
            "TTS inference process is opened",
        ]
        else False
    )


def Make_Sound_TTs(conf, text):
    """开始TTS推理"""
    i = 0
    while i < 60:
        try:
            client = Client("http://soVits:9872/")
            result = client.predict(
                conf["sound"],
                conf["refer"],
                conf["language"],
                f"{text}",
                conf["language"],
                "Cut per 50 characters",
                5,
                1,
                1,
                True,
                fn_index=3,
            )
        except BaseException as err:
            # print(f"Err: {err}")
            i += 1
        else:
            return result
        time.sleep(1)
    print("连接服务器失败")
    return False
